"""
@Author    : ghenyar
@Time      : 2025/9/15 17:37
@File      : agreement_model
@Desc      : 
"""
from datetime import datetime
from typing import Optional

from sqlalchemy import UniqueConstraint, Enum as SAEnum, String, Integer, Text, DateTime, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func
from app.enum.agreement import AgreementType, AgreementStatus
from app.models import DatabaseModel, table_prefix


class AgreementModel(DatabaseModel):
    __tablename__ = f"{table_prefix}agreements"
    __table_args__ = (
        UniqueConstraint("types", "version", name="uq_agreement_type_version"),
        {"comment": "协议管理表"}
    )
    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True, comment="协议ID")
    types: Mapped[AgreementType] = mapped_column(
        SAEnum(AgreementType), nullable=False, comment="协议类型"
    )
    title: Mapped[str] = mapped_column(String(100), nullable=False, comment="协议标题")
    content: Mapped[str] = mapped_column(Text, nullable=False, comment="协议内容")
    version: Mapped[str] = mapped_column( String(20), nullable=False, comment="版本号, 同一类型下应是唯一的")
    status: Mapped[AgreementStatus] = mapped_column(
        SAEnum(AgreementStatus), default=AgreementStatus.DRAFT, nullable=False, comment="状态：0=草稿,1=已发布,2=已归档"
    )
    created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now(),
                                                 comment="创建时间")
    updated_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, onupdate=func.now(),
                                                        comment="更新时间")

    # -------------------- 属性 --------------------
    @property
    def type_label(self) -> str:
        return AgreementType.get_label(self.types)

    @property
    def status_label(self) -> str:
        return AgreementStatus.get_label(self.status)

    @property
    def is_draft(self) -> bool:
        return self.status == AgreementStatus.DRAFT

    @property
    def is_published(self) -> bool:
        return self.status == AgreementStatus.PUBLISHED

    @property
    def is_archived(self) -> bool:
        return self.status == AgreementStatus.ARCHIVED

    @classmethod
    async def get_latest_version(
        cls, session: AsyncSession, agreement_type: AgreementType,PUBLISHED:bool=False
    ) -> Optional["AgreementModel"]:
        where=[cls.types==agreement_type]
        if PUBLISHED:
            where.append(cls.status==AgreementStatus.PUBLISHED)

        return (
            await session.scalars(
                select(cls)
                .where(*where)
                .order_by(cls.version.desc())
                .limit(1)
            )
        ).first()

